//  2020-02-09
//  author: lbfamous
//  desc:


cc.Class({
    extends: cc.Component,

    properties: {

        starPrefab:{
            default:null,
            type:cc.Prefab
        },
        maxStarDuration:0,
        minStarDuration:0,
        ground:{
            default:null,
            type:cc.Node
        },
        player:{
            default: null,
            type:cc.Node
        },

        scoreDisplay:{
            default:null,
            type:cc.Label,
        },

        scoreAudio:{

            default:null,
            type:cc.AudioClip,
        }

    },


    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        this.groundY = this.ground.y + this.ground.height /2

        this.timer = 0;
        this.starDuration = 0;
        this.spawnNewStar(); //-新星星
        this.score = 0;

    },

    start () {

    },

    update (dt) {

        if(this.timer > this.starDuration){
            this.gameOver();
            return;
        }
        this.timer +=dt;
    },


    spawnNewStar(){

        this.starDuration = this.minStarDuration + Math.random() * (this.maxStarDuration - this.minStarDuration);
        this.star = 0;
        let newStar = cc.instantiate(this.starPrefab)
        this.node.addChild(newStar)
        newStar.setPosition(this.getNewStarPosition())
        newStar.getComponent('Star').game = this
    },

    getNewStarPosition() {

        let randX = 0
        let randY = this.groundY + Math.random() * this.player.getComponent('Player').jumpHeight + 50
        let maxX = this.node.width /2
        randX = (Math.random() - 0.5) * 2 * maxX
        return cc.v2(randX,randY)

    },

    gainScore() {        
        this.score += 1;
        this.scoreDisplay.string = "Score: " + this.score;

        cc.audioEngine.playEffect(this.scoreAudio,false);
    },

    gameOver(){

        this.player.stopAllActions();
        cc.director.loadScene('game');  //-重新启动game
    }
});
